{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Create reproducible pipelines"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Reproducibility is important for testing, replicating results, and can even be used to [improve image quality](https://huggingface.co/docs/diffusers/main/en/using-diffusers/reusing_seeds). However, the randomness in diffusion models is a desired property because it allows the pipeline to generate different images every time it is run. While you can't expect to get the exact same results across platforms, you can expect results to be reproducible across releases and platforms within a certain tolerance range. Even then, tolerance varies depending on the diffusion pipeline and checkpoint.\n",
    "\n",
    "This is why it's important to understand how to control sources of randomness in diffusion models or use deterministic algorithms.\n",
    "\n",
    "<Tip>\n",
    "\n",
    "💡 We strongly recommend reading PyTorch's [statement about reproducibility](https://pytorch.org/docs/stable/notes/randomness.html):\n",
    "\n",
    "> Completely reproducible results are not guaranteed across PyTorch releases, individual commits, or different platforms. Furthermore, results may not be reproducible between CPU and GPU executions, even when using identical seeds.\n",
    "\n",
    "</Tip>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Control randomness"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "During inference, pipelines rely heavily on random sampling operations which include creating the \n",
    "Gaussian noise tensors to denoise and adding noise to the scheduling step.\n",
    "\n",
    "Take a look at the tensor values in the [DDIMPipeline](https://huggingface.co/docs/diffusers/main/en/api/pipelines/ddim#diffusers.DDIMPipeline) after two inference steps:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from diffusers import DDIMPipeline\n",
    "import numpy as np\n",
    "\n",
    "model_id = \"google/ddpm-cifar10-32\"\n",
    "\n",
    "# load model and scheduler\n",
    "ddim = DDIMPipeline.from_pretrained(model_id)\n",
    "\n",
    "# run pipeline for just two steps and return numpy tensor\n",
    "image = ddim(num_inference_steps=2, output_type=\"np\").images\n",
    "print(np.abs(image).sum())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Running the code above prints one value, but if you run it again you get a different value. What is going on here? \n",
    "\n",
    "Every time the pipeline is run, [`torch.randn`](https://pytorch.org/docs/stable/generated/torch.randn.html) uses a different random seed to create Gaussian noise which is denoised stepwise. This leads to a different result each time it is run, which is great for diffusion pipelines since it generates a different random image each time.\n",
    "\n",
    "But if you need to reliably generate the same image, that'll depend on whether you're running the pipeline on a CPU or GPU."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### CPU"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To generate reproducible results on a CPU, you'll need to use a PyTorch [`Generator`](https://pytorch.org/docs/stable/generated/torch.randn.html) and set a seed:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "from diffusers import DDIMPipeline\n",
    "import numpy as np\n",
    "\n",
    "model_id = \"google/ddpm-cifar10-32\"\n",
    "\n",
    "# load model and scheduler\n",
    "ddim = DDIMPipeline.from_pretrained(model_id)\n",
    "\n",
    "# create a generator for reproducibility\n",
    "generator = torch.Generator(device=\"cpu\").manual_seed(0)\n",
    "\n",
    "# run pipeline for just two steps and return numpy tensor\n",
    "image = ddim(num_inference_steps=2, output_type=\"np\", generator=generator).images\n",
    "print(np.abs(image).sum())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now when you run the code above, it always prints a value of `1491.1711` no matter what because the `Generator` object with the seed is passed to all the random functions of the pipeline.\n",
    "\n",
    "If you run this code example on your specific hardware and PyTorch version, you should get a similar, if not the same, result.\n",
    "\n",
    "<Tip>\n",
    "\n",
    "💡 It might be a bit unintuitive at first to pass `Generator` objects to the pipeline instead of \n",
    "just integer values representing the seed, but this is the recommended design when dealing with \n",
    "probabilistic models in PyTorch as `Generator`'s are *random states* that can be \n",
    "passed to multiple pipelines in a sequence.\n",
    "\n",
    "</Tip>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### GPU"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Writing a reproducible pipeline on a GPU is a bit trickier, and full reproducibility across different hardware is not guaranteed because matrix multiplication - which diffusion pipelines require a lot of - is less deterministic on a GPU than a CPU. For example, if you run the same code example above on a GPU:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "from diffusers import DDIMPipeline\n",
    "import numpy as np\n",
    "\n",
    "model_id = \"google/ddpm-cifar10-32\"\n",
    "\n",
    "# load model and scheduler\n",
    "ddim = DDIMPipeline.from_pretrained(model_id)\n",
    "ddim.to(\"cuda\")\n",
    "\n",
    "# create a generator for reproducibility\n",
    "generator = torch.Generator(device=\"cuda\").manual_seed(0)\n",
    "\n",
    "# run pipeline for just two steps and return numpy tensor\n",
    "image = ddim(num_inference_steps=2, output_type=\"np\", generator=generator).images\n",
    "print(np.abs(image).sum())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The result is not the same even though you're using an identical seed because the GPU uses a different random number generator than the CPU.\n",
    "\n",
    "To circumvent this problem, 🧨 Diffusers has a [randn_tensor()](https://huggingface.co/docs/diffusers/main/en/api/utilities#diffusers.utils.randn_tensor) function for creating random noise on the CPU, and then moving the tensor to a GPU if necessary. The `randn_tensor` function is used everywhere inside the pipeline, allowing the user to **always** pass a CPU `Generator` even if the pipeline is run on a GPU. \n",
    "\n",
    "You'll see the results are much closer now!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "from diffusers import DDIMPipeline\n",
    "import numpy as np\n",
    "\n",
    "model_id = \"google/ddpm-cifar10-32\"\n",
    "\n",
    "# load model and scheduler\n",
    "ddim = DDIMPipeline.from_pretrained(model_id)\n",
    "ddim.to(\"cuda\")\n",
    "\n",
    "# create a generator for reproducibility; notice you don't place it on the GPU!\n",
    "generator = torch.manual_seed(0)\n",
    "\n",
    "# run pipeline for just two steps and return numpy tensor\n",
    "image = ddim(num_inference_steps=2, output_type=\"np\", generator=generator).images\n",
    "print(np.abs(image).sum())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<Tip>\n",
    "\n",
    "💡 If reproducibility is important, we recommend always passing a CPU generator.\n",
    "The performance loss is often neglectable, and you'll generate much more similar \n",
    "values than if the pipeline had been run on a GPU.\n",
    "\n",
    "</Tip>\n",
    "\n",
    "Finally, for more complex pipelines such as [UnCLIPPipeline](https://huggingface.co/docs/diffusers/main/en/api/pipelines/unclip#diffusers.UnCLIPPipeline), these are often extremely \n",
    "susceptible to precision error propagation. Don't expect similar results across \n",
    "different GPU hardware or PyTorch versions. In this case, you'll need to run \n",
    "exactly the same hardware and PyTorch version for full reproducibility."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Deterministic algorithms"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can also configure PyTorch to use deterministic algorithms to create a reproducible pipeline. However, you should be aware that deterministic algorithms may be slower than nondeterministic ones and you may observe a decrease in performance. But if reproducibility is important to you, then this is the way to go!\n",
    "\n",
    "Nondeterministic behavior occurs when operations are launched in more than one CUDA stream. To avoid this, set the environment varibale [`CUBLAS_WORKSPACE_CONFIG`](https://docs.nvidia.com/cuda/cublas/index.html#results-reproducibility) to `:16:8` to only use one buffer size during runtime.\n",
    "\n",
    "PyTorch typically benchmarks multiple algorithms to select the fastest one, but if you want reproducibility, you should disable this feature because the benchmark may select different algorithms each time. Lastly, pass `True` to [`torch.use_deterministic_algorithms`](https://pytorch.org/docs/stable/generated/torch.use_deterministic_algorithms.html) to enable deterministic algorithms."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "os.environ[\"CUBLAS_WORKSPACE_CONFIG\"] = \":16:8\"\n",
    "\n",
    "torch.backends.cudnn.benchmark = False\n",
    "torch.use_deterministic_algorithms(True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now when you run the same pipeline twice, you'll get identical results."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "from diffusers import DDIMScheduler, StableDiffusionPipeline\n",
    "import numpy as np\n",
    "\n",
    "model_id = \"runwayml/stable-diffusion-v1-5\"\n",
    "pipe = StableDiffusionPipeline.from_pretrained(model_id).to(\"cuda\")\n",
    "pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)\n",
    "g = torch.Generator(device=\"cuda\")\n",
    "\n",
    "prompt = \"A bear is playing a guitar on Times Square\"\n",
    "\n",
    "g.manual_seed(0)\n",
    "result1 = pipe(prompt=prompt, num_inference_steps=50, generator=g, output_type=\"latent\").images\n",
    "\n",
    "g.manual_seed(0)\n",
    "result2 = pipe(prompt=prompt, num_inference_steps=50, generator=g, output_type=\"latent\").images\n",
    "\n",
    "print(\"L_inf dist = \", abs(result1 - result2).max())\n",
    "\"L_inf dist =  tensor(0., device='cuda:0')\""
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 4
}
